import type {
  LoginFormData,
  LoginResponse,
  SocialLoginType,
  SocialLoginResponse,
} from "../pages/Login/types";
import axios from "axios";

import { message } from "antd";

import { getSession } from "../utils/storage";

/**
 * @description 创建 axios 实例
 */
const api = axios.create({
  baseURL: "/api",
  timeout: 10000,
});

/**
 * @description 请求拦截器
 */
api.interceptors.request.use(
  (config) => {
    const url: any = config.url;

    if (url.indexOf("user/login") > -1) {
      // config.headers.common.Authorization = '';
    } else {
      const token = getSession("token");

      if (typeof token !== "undefined" && token) {
        config.headers.token = token;
      } else {
        window.location.href = window.location.origin + "/login";
      }
    }

    return config;
  },

  (error) => {
    return Promise.reject(error);
  }
);

/**
 * @description 响应拦截器
 */
api.interceptors.response.use(
  (response) => {
    console.log("response", response);

    if (response.data.code === 0) {
      return response.data;
    } else {
      message.error(response.data.result);
    }

    return Promise.resolve(response.data);
  },

  (error) => {
    console.log("error", error);

    if (error.response?.status === 401) {
      clearAuth();
      window.location.href = "/login";
    }

    return Promise.reject(error);
  }
);

/**
 * @description 社交媒体登录配置
 */
const SOCIAL_CONFIG = {
  wechat: {
    appId: "your_wechat_app_id",
    redirectUri: encodeURIComponent(
      window.location.origin + "/auth/wechat/callback"
    ),
    scope: "snsapi_userinfo",
  },

  alipay: {
    appId: "your_alipay_app_id",
    redirectUri: encodeURIComponent(
      window.location.origin + "/auth/alipay/callback"
    ),
    scope: "auth_user",
  },
};

/**
 * @description 登录服务
 */
export const authService = {
  /**
   * @description 用户登录
   * @param params 登录表单数据
   * @returns Promise<LoginResponse>
   */
  login: (params: LoginFormData) => {
    return new Promise(function (resolve, reject) {
      api
        .post("user/login", params)
        .then((headers) => {
          resolve(headers);
        })
        .catch((data) => {
          reject(data);
        });
    });
  },
  logout: (params: any) => {
    return new Promise(function (resolve, reject) {
      api
        .post("user/logout", params)
        .then((headers) => {
          resolve(headers);
        })
        .catch((data) => {
          reject(data);
        });
    });
  },

  /**
   * @description 获取社交媒体登录URL
   * @param type 社交媒体类型
   * @returns string 登录URL
   */
  getSocialLoginUrl: (type: SocialLoginType): string => {
    const config = SOCIAL_CONFIG[type];
    const state = Math.random().toString(36).substring(7);

    // 存储state用于回调验证
    localStorage.setItem(
      `$ {
        type
      }

      _state`,
      state
    );

    switch (type) {
      case "wechat":
        return `https: //open.weixin.qq.com/connect/qrconnect?appid=${config.appId}&redirect_uri=${config.redirectUri}&response_type=code&scope=${config.scope}&state=${state}#wechat_redirect`;
      case "alipay":
        return `https: //openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=${config.appId}&redirect_uri=${config.redirectUri}&scope=${config.scope}&state=${state}`;
      default:
        throw new Error("不支持的登录类型");
    }
  },

  /**
   * @description 处理社交媒体登录回调
   * @param type 社交媒体类型
   * @param response 回调响应数据
   * @returns Promise<LoginResponse>
   */
  handleSocialLogin: async (
    type: SocialLoginType,
    response: SocialLoginResponse
  ): Promise<LoginResponse> => {
    try {
      // 验证state
      const savedState = localStorage.getItem(`$ {
          type
        }

        _state`);

      if (!savedState || savedState !== response.state) {
        throw new Error("无效的登录请求");
      }

      // 清除state
      localStorage.removeItem(`$ {
          type
        }

        _state`);

      // 调用后端接口处理社交媒体登录
      const result = await api.post<LoginResponse>(
        `/auth/$ {
          type
        }

        /callback`,
        response
      );

      // 存储 token
      if (result.data.token) {
        localStorage.setItem("token", result.data.token);
      }

      return result.data;
    } catch (error) {
      if (axios.isAxiosError(error)) {
        throw new Error(error.response?.data?.message || "社交媒体登录失败");
      }

      throw error;
    }
  },
};

/**
 * @description 获取存储的token
 * @returns string | null
 */
export const getToken = (): string | null => {
  return localStorage.getItem("token");
};

/**
 * @description 清除认证信息
 */
export const clearAuth = (): void => {
  localStorage.removeItem("token");
};
